package com.ruima.study.arithmetic.sortdemo.practice;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * <p>合并重叠数组</p>
 * <p>
 * <p>Copyright (c) 2024/11/15 15:36, 科大讯飞 All Rights Reserve</p>
 *
 * @author ruima6
 * @version [V1.0]
 */
public class demo5 {
    public static void main(String[] args) {
        int[][] arr = {{1, 3}, {2, 6}, {5, 10}, {15, 18}};

        int[][] merge = new demo5().merge(arr);
        for (int[] ints : merge) {
            System.out.println(ints[0] + ";;" + ints[1]);
        }
    }


    public int[][] merge(int[][] intervals) {

        int preOne = intervals[0][0];
        int preTwo = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            int valueOne = intervals[i][0];
            int valueTwo = intervals[i][1];

            if (valueOne > preTwo){
                preOne = valueOne;
                preTwo = valueTwo;
            }else {
                int valueOneNew = Math.min(preOne,valueOne);
                int valueTwoNew = Math.max(preTwo,valueTwo);

                intervals[i-1][0] = -1;
                intervals[i-1][1] = -1;

                intervals[i][0] = valueOneNew;
                intervals[i][1] = valueTwoNew;

                preOne = valueOneNew;
                preTwo = valueTwoNew;
            }
        }

        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < intervals.length; i++) {
            if (!(intervals[i][0] == -1 && intervals[i][1] == -1)){
                map.put(intervals[i][0], intervals[i][1]);
            }
        }

        int[][] result = new int[map.size()][2];
        int index = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            result[index][0] = entry.getKey();
            result[index][1] = entry.getValue();
            index++;
        }
        return result;
    }

}
